﻿using Light.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Light.Framework
{
    /// <summary>
    /// SQL日志记录类
    /// </summary>
    class SQLLoger
    {
        /// <summary>
        /// 记录程序执行的SQL语句
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="listParams"></param>
        public static void Write(string sql, params IDataParameter[] listParams)
        {
            Dictionary<DbType, string> dic = new Dictionary<DbType, string>();
            dic.Add(DbType.Byte, "tinyint");
            dic.Add(DbType.Int16, "smallint");
            dic.Add(DbType.Int32, "int");
            dic.Add(DbType.Int64, "bigint");
            dic.Add(DbType.String, "varchar(500)");
            dic.Add(DbType.AnsiString, "varchar(500)");
            dic.Add(DbType.Boolean, "bit");
            dic.Add(DbType.Decimal, "money");
            dic.Add(DbType.Double, "float");
            dic.Add(DbType.DateTime, "datetime");
            dic.Add(DbType.Single, "real");
            dic.Add(DbType.Guid, "uniqueidentifier");

            if (ApplicationSetting.ReadAppSetting("sql.log", false))
            {
                string filename = "sql.log";
                TextHelper.Console(filename, sql + "\r\n", true);

                if (listParams != null)
                {
                    StringBuilder builder = new StringBuilder();
                    foreach (var item in listParams)
                    {
                        var dicValue = dic.SingleOrDefault(w => w.Key == item.DbType).Value;
                        builder.Append(string.Format(" DECLARE {0} {2} = '{1}' \r\n", item.ParameterName, item.Value, dicValue));
                    }
                    TextHelper.Console(filename, builder.ToString() + "\r\n");
                }
            }
        }
    }
}
